<?php
/**
 * @author qingyu8@staff.weibo.com
 * @date 2018/05/20
 */
namespace common\tool;

use Money\Converter;
use Money\Currencies\ISOCurrencies;
use Money\Exchange\FixedExchange;
use Money\Money;
use yii;
use Money\Currency as MoneyCurrency;

class Currency {
    public static $exchange = null;
    public static $exchageMap = null;

    public static function usd2cny() {
        $n = new Money(100, new MoneyCurrency('CNY'));
    }

    public static function cny2usd() {
    }

    /**
     * 欧分转人民币分，整型
     */
    public static function eur2cny($from) {
        $n = new Money($from, new MoneyCurrency('EUR'));
        $converter = new Converter(new ISOCurrencies(), self::getExchange());

        $new = $converter->convert($n, new MoneyCurrency('CNY'));
        return $new->getAmount();
    }

    public static function getEur2CnyRate() {
        $r = self::getExchangeMap();
        return $r['EUR']['CNY'];
    }

    /*
     * 欧元转人民币元
     */
    public static function eur2cnyYuan($from) {
        return (int)self::eur2cny($from * 100) / 100;
    }

    public static function cny2eur() {
    }

    public static function getExchange() {
        if (!self::$exchange) {
            self::$exchange = new FixedExchange(self::getExchangeMap());
        }
        return self::$exchange;
    }

    public static function getExchangeMap() {
        if (!isset(self::$exchageMap)) {
            self::$exchageMap = require Yii::$app->params['env']['DATA_PATH'] . 'exchange-rate.php';
        }
        return self::$exchageMap;
    }
}
